(function( $, undefined ) {

/*
	\name ru Checkboxlist
	\description ru Список флажков выбора да/нет.
	\is_container 0
	\save true
*/
$.widget("ui.ajajform_checkboxlist",$.ui.ajajform_widget, {
	options: {
		// \type cssclass
		cssclass: "afw-checkboxlist",
		available: [],
		checked: [],
		width: 200,
		// \type text
		htmltemplate: '<div class="af-label"></div><div class="af-edit"><div class="checkboxes"></div><div class="af-error"></div></div><div style="clear: both;"></div>',
		checkboxtemplate: '<span class="item"><input type="checkbox" class="" name="" value="1"/><span class="name"></span></span>',
		// \type text
		label: "",
		// \type function
		validate: null
	},
	_create: function() {
		this.element.addClass(this.options.cssclass);
		var t=this.options.htmltemplate;
		this.element.append(t);
		this.refreshLabel();
		this.refreshWidth();
		this.refreshAvailable();
		this.refreshChecked();
	},
	refreshWidth: function() {
		$(".af-edit",this.element).width(this.options.width);
	},
	refreshAvailable: function() {
		var cbs=$(".checkboxes",this.element).empty();
	
		for (var i=0;i<this.options.available.length;i++) {
			var av=this.options.available[i];
			var cb=$(this.options.checkboxtemplate).appendTo(cbs);
			$(".name",cb).text(av.name);
			$("input",cb).prop("name",this.options.name+"-"+av.id);
		}
		cbs.append('<div style="clear: both;"></div>');
	},
	refreshChecked: function() {
		$(".checkboxes input",this.element).prop("checked",false);
		for (var i=0;i<this.options.checked.length;i++) {
			var c=this.options.checked[i];
			$(".checkboxes input[name='"+this.options.name+"-"+c+"']",this.element).prop("checked",true);
		}
	},
	refreshError: function(e) {
		$(".af-error",this.element).text(e==null?"":e);
	},
	refreshLabel: function() {
		$(".af-label",this.element).text(this.options.label);
	},
	destroy: function() {
	},
	validate: function() {
		return false;
	},
	postvalue: function(r) {
		var sel=$(".checkboxes .item input:checked",this.element);
		for (var i=0;i<sel.length;i++) {
			var item=sel[i];
			r[item.name]=1;
		}
	}
});

})( jQuery );
